package com.kye.express.business.welfare;

import android.app.Dialog;
import android.databinding.DataBindingUtil;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.utils.NetworkMonitorUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.business.login.LoginActivity;
import com.kye.express.business.welfare_integral.IntegralCenterActivity;
import com.kye.express.databinding.FragmentMainWelfareBinding;
import com.kye.express.utils.AppUtil;
import com.kye.express.utils.StringUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.express.view.reclyerview.GridSpacingItemDecoration;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.integral.request.ResultGetIntegralModel;
import com.kye.model.bean.user.User;
import com.kye.model.bean.welfare.ResponseWelfareLiPinDH;
import com.kye.model.constant.Constants;
import com.kye.base.Logger;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.text.DecimalFormat;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 礼物界面 Fragment
 * <p>
 * Created by SkyYu on 2017/12/17
 */
public class WelfareFragment extends BaseAppCompatFragment implements WelfareContract.WelfareView {

    private View mRootView;
    private FragmentMainWelfareBinding mDataBinding;
    private WelfareContract.WelfarePresenter mPresenter;
    private MultiTypeAdapter mAdapter;
    private Dialog mLoadingDialog = null;
    private User tempUser;

    public static WelfareFragment newInstance() {
        Bundle args = new Bundle();
        WelfareFragment fragment = new WelfareFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_main_welfare, container, false);
        return mRootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initEvent();
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) mPresenter.unbind();
    }

    private void initView() {
        initBinding();
        initPresenter();
        initAdaptation();
    }

    private void initEvent() {
        mDataBinding.smartrefreshlayoutWelfare.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                isLogin(tempUser);
            }

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {

            }
        });

        RxView.clicks(mDataBinding.linearlayoutWelfareIntegralrecord)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(object ->
                        IntegralCenterActivity.startActivity(getActivity())
                );
    }

    private void initData() {
        initAdapter();
    }

    private void initAdaptation() {
        adaptationHeight();
    }

    private void initBinding() {
        mDataBinding = DataBindingUtil.bind(mRootView);
    }

    private void initPresenter() {
        mPresenter = new WelfareContract.WelfarePresenter();
        mPresenter.bind(this);
    }

    public void initAdapter() {
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(ResponseWelfareLiPinDH.ResultBean.class, new WelfareItemViewBinder(getActivity()));
        mAdapter.setItems(new Items());
        mDataBinding.recyclerviewWelfarePlatform.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        mDataBinding.recyclerviewWelfarePlatform.setItemAnimator(new DefaultItemAnimator());
        mDataBinding.recyclerviewWelfarePlatform.addItemDecoration(new GridSpacingItemDecoration(2, 18, false));
        mDataBinding.recyclerviewWelfarePlatform.setAdapter(mAdapter);
    }

    /**
     * 针对4.4手机的标题栏高度适配
     */
    public void adaptationHeight() {
        if (AppUtil.getSDKVersion() == 19 || AppUtil.getSDKVersion() == 20) {
            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, AppUtil.getStatusBarHeight(), 0, 0);
            mDataBinding.linearlayoutWelfare.setLayoutParams(lp);
        }
    }

    @Override
    public void onLoadUser(User user) {
        tempUser = user;
        isLogin(user);
    }

    @Override
    public void onLoadIntegral(ResultGetIntegralModel bean) {
        if (bean != null) {
            double systemIntegral = bean.systemIntegral / 10000;
            String integral = StringUtils.decimalFormatTwo(systemIntegral);
            mDataBinding.textviewWelfareIntegral.setText(integral);
        } else {
            Logger.d("WelfareFragment - onLoadIntegral - bean is null ");
        }
        closeDialog();
        mDataBinding.smartrefreshlayoutWelfare.finishRefresh();
    }

    @Override
    public void onLoadIntegralApiError(OpenApiResult<ResultGetIntegralModel> result, int code, String msg) {
        ToastManager.show(getActivity(), msg);
        Logger.d("WelfareFragment - onLoadIntegralApiError - result:" + result + ",code:" + code + ",msg:" + msg);
        closeDialog();
        mDataBinding.smartrefreshlayoutWelfare.finishRefresh();
    }

    @Override
    public void onLoadWelFareList(OpenApiResult<ResponseWelfareLiPinDH> result) {
        if (result != null) {
            if (result.getCode() == Constants.ResponseCode_SUCCESS) {
                ResponseWelfareLiPinDH data = result.getData();
                if (data != null && data.getResult().size() > 0) {
                    Items items = (Items) mAdapter.getItems();
                    items.clear();
                    items.addAll(data.getResult());
                    mAdapter.setItems(items);
                    mAdapter.notifyDataSetChanged();
                } else {
                    Logger.d("WelfareFragment - onLoadWelFareList - size is 0");
                }
            } else {
                ToastManager.show(getActivity(), result.getMsg());
            }
        } else {
            Logger.d("WelfareFragment - onLoadWelFareList - bean is null");
        }
        closeDialog();
        mDataBinding.smartrefreshlayoutWelfare.finishRefresh();
    }

    @Override
    public void onLoadWelFareListApiError(OpenApiResult<ResponseWelfareLiPinDH> result, int code, String msg) {
        ToastManager.show(getActivity(), msg);
        Logger.d("WelfareFragment - onLoadWelFareListApiError - result:" + result + ",code:" + code + ",msg:" + msg);
        closeDialog();
        mDataBinding.smartrefreshlayoutWelfare.finishRefresh();
    }

    @Override
    public void onOtherError(Throwable e) {
        ToastManager.show(getActivity(), getString(R.string.common_net_error));
        Logger.d("WelfareFragment - onOtherError : " + e.getMessage());
        e.printStackTrace();
        closeDialog();
        mDataBinding.smartrefreshlayoutWelfare.finishRefresh();
    }

    private void isLogin(User user) {
        if (user == null || !user.isLogin()) {
            ToastManager.show(getActivity(), getString(R.string.common_login));
            LoginActivity.startActivity(getActivity());
        } else {
            request(Constants.JD_KYSIGN, user.getPhone());
        }
    }

    private void request(String appSign, String phone) {
        NetworkMonitorUtils.networkObservable(getActivity())
                .compose(bindToLifecycleDestroy())
                .map((connectivity) -> {
                    NetworkInfo.State state = connectivity.getState();
                    switch (state) {
                        case CONNECTED:
                        case CONNECTING:
                            return true;
                        case DISCONNECTED:
                        case DISCONNECTING:
                            return false;
                        default:
                            return false;
                    }
                })
                .subscribe((Boolean) -> {
                    if (Boolean) {
                        showDialog();
                        mPresenter.requestToGetAvailableIntegral(appSign, phone);
                        mPresenter.requestToGetWelfare();
                    } else {
                        ToastManager.show(getActivity(), getString(R.string.common_net_error));
                    }
                });
    }

    private void showDialog() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new KyeProgressDialog.Builder(getActivity()).build();
        }
        mLoadingDialog.show();
    }

    private void closeDialog() {
        mLoadingDialog.dismiss();
    }
}